<?php
namespace soa\partner\ane;

use artisan\cache;
use soa\common\RemoteDB;
use soa\service;

class BaseInformation extends AneClient
{
    const PATH = '/upload/aneCopy/';
//    const PATH = 'd:/wamp/www/upload/aneCopy';

    private $cacheKey;

    private $cacheTime = 3600;

    private $copyFile;

    public $cache;

    public $exceptSignType = [
        100000 => '货损类',
        100001 => '拒收类',
        100002 => '寄件网点原因',
        100003 => '客户自提',
        100004 => '生鲜水果/违禁品销毁',
        100005 => '联系不上收件人',
        100006 => '行政机构查扣',
        100007 => '网点退网',
    ];

    public function __construct()
    {
        parent::__construct();

        $this->cache = cache::connect('pda');
    }

    /**
     * 上一站下一站
     *
     * @param $thirdBranchId
     * @return array|bool|mixed|null|string
     */
    public function prevNextSite($thirdBranchId)
    {
        $this->keyBuilder(__FUNCTION__, $thirdBranchId);

        $result = $this->cache->get($this->cacheKey);

        if(empty($result) || !is_array($result)) {
            $result = $this->send('queryLimitSiteService',[
                'siteId' => $thirdBranchId,
                'key'    => 3,
            ]);

            $this->cacheTime = 10;
            $this->setCache($result);
        }

        //注释
        $return = [];
        if($result && is_array($result)) {
            foreach ($result as $item) {
                if($item['limitSiteId'] && $item['limitSiteName']){
                    $return[] = [
                        'branch_id'    => $item['limitSiteId'],
                        'name'         => $item['limitSiteName'],
                        'site_type_id' => $item['limitSiteTypeId'],
                        'type'         => $item['limitType'] == 2 ? '下一站' : '上一站',
                    ];
                }
            }
        }

        return $return;
    }

    /**
     * 收件时获取物料
     *
     * @param $thirdBranchId
     * @return array|bool|mixed|null|string
     */
    public function getIssueList($thirdBranchId)
    {
        $this->keyBuilder(__FUNCTION__, $thirdBranchId);

        $return = $this->cache->get($this->cacheKey);

        if(empty($return)){
            $return = $this->getIssueListBySiteId($thirdBranchId);
            if($this->getCode()){
                $return = [];
                $result = (new RemoteDB('kd_pda','tbl_issue_list_ane'))->getAll(['3rd_branch_id'=>$thirdBranchId]);
                foreach($result as $item){
                    if($item['ewb_start'] && $item['ewb_end']){
                        $return[] = [
                            'ewbStart' => $item['ewb_start'],
                            'ewbEnd'   => $item['ewb_end'],
                        ];
                    }
                }
            }
            if($return && is_array($return)){
                $this->cacheTime = 10;
                $this->setCache($return);
            }
        }
        return $return;
    }

    /**
     * @param $thirdBranchId
     * @return array
     */
    public function getIssueListBySiteId($thirdBranchId)
    {
        $data = [
            'useSiteId' => $thirdBranchId,
            'beginTime' => strtotime(date('2000-01-01 00:00:00')) * 1000,
            'endTime'   => strtotime(date('Y-12-31 00:00:00')) * 1000,
        ];
        return $this->send('issueListService',$data,['TIMEOUT'=>5]);
    }

    /**
     * 获取签收类型
     *
     * @return array
     */
    public function getSignType()
    {
        $this->keyBuilder(__FUNCTION__);

        $return = $this->cache->get($this->cacheKey);

        if(empty($return)){
            $return = [];
            $data = ['downloadTime' => strtotime('2000-01-01')*1000];
            $result = $this->send('signTypeService',$data);
            if($result && is_array($result)){
                foreach($result as $item){
                    if(!empty($item['rdStatus']) && !empty($item['dictName'])) {
                        $return[$item['dictId']] = [
                            'signId'     => $item['dictId'],
                            'signCode'   => $item['dictCode'],
                            'signType'   => $item['dictName'],
                            'signPinyin' => $item['dictPinyin'],
                        ];
                    }
                }
                $this->setCache($return, 1);
            }
            if(empty($return)){
                $return = $this->getCopyFile();
            }
        }

        return $this->buildReturn($return);
    }

    /**
     * 获取问题件类型
     *
     * @return array
     */
    public function getQuestionList()
    {
        $this->keyBuilder(__FUNCTION__);

        $return = $this->cache->get($this->cacheKey);

        if(empty($return)){
            $return = [];
            $data = ['downloadTime' => strtotime('2000-01-01')*1000];
            $result = $this->send('questionListService',$data);
            if($result && is_array($result)){
                foreach($result as $item){
                    if(!empty($item['rdStatus']) && !empty($item['problemTypeId']) && !empty($item['problemTypeName'])){
                        $return[$item['problemTypeId']] = [
                            'badWayBillCode' => $item['problemTypeId'],//兼容以前巴枪上传的参数，以免混淆
                            'badWayBillDesc' => $item['problemTypeName'],
                        ];
                    }
                }
                $this->setCache($return, 1);
            }
            if(empty($return)){
                $return = $this->getCopyFile();
            }
        }

        return $this->buildReturn($return);
    }

    /**
     * 获取运单号规则
     *
     * @param bool $forceUpdate
     * @return array|bool|mixed|null|string
     */
    public function getRule($forceUpdate = false)
    {
        $this->keyBuilder(__FUNCTION__);

        if(empty($forceUpdate)){
            $return = $this->cache->get($this->cacheKey);
        }

        if(empty($return)){
            $return = [];
            $result = $this->send('billRuleService');
            if($result && is_array($result)){
                foreach($result as $item){
                    if(!empty($item['ewbRuleValue']) && !empty($item['ewbTypeName'])){
                        $return[] = $item;
                    }
                }
                $this->setCache($return, 1);
            }
            if(empty($return)){
                $return = $this->getCopyFile();
            }
        }

        return $return;
    }

    /**
     * @param $key
     * @param string $key1
     * @return string
     */
    public function keyBuilder($key, $key1 = '')
    {
        if($key && is_string($key)){
            $this->cacheKey = 'zzzzz_ane_' . ucfirst($key);
            $this->copyFile = static::PATH . $this->cacheKey . '.txt';
            if($key1){
                $this->cacheKey = $this->cacheKey . $key1;
            }
        }
        return $this->cacheKey;
    }

    /**
     * @param $data
     * @param int $putFile
     */
    private function setCache($data, $putFile = 0)
    {
        if(!empty($data) && is_array($data)){
            $this->cache->set($this->cacheKey,$data,$this->cacheTime);
            if($putFile){
                if(!file_exists(static::PATH)){
                    mkdir(static::PATH, 0777, true);
                }
                file_put_contents($this->copyFile, json_encode($data));
            }
        }
    }

    /**
     * @return array|mixed
     */
    private function getCopyFile()
    {
        if(file_exists($this->copyFile)){
            $return = json_decode(file_get_contents($this->copyFile),true);
            if(!empty($return) && is_array($return)) {
                $this->cache->set($this->cacheKey, $return, $this->cacheTime);
            }
        }else{
            $return = [];
        }
        return $return;
    }

    /**
     * @param $data
     * @return array
     */
    private function buildReturn($data)
    {
        if(!empty($data) && is_array($data)){
            return $data;
        }else{
            $msg = 0 != $this->getCode() ? ($this->getMsg()) : '接口暂时获取不到数据，请稍后重试！';
            return $msg;
        }
    }

}